package cn.afactory.tygz.ui.base.views.search;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.ui.base.entity.SearchHistoryEntity;

/**
 * Created by Kenneth on 15/9/13.
 */
public class SearchHistory {
    private static final int MAX_HISTORY_LEN = 6;
    private static final String PREF_SEARCH_NAME = "pref_search_history";
    private static final String PREF_KEY_HISTORY = "key_search_history";
    private static SearchHistory mInstance;
    private WeakReference<HistoryList> mHistory = new WeakReference<HistoryList>(null);
    private Context mAppContext;

    private SearchHistory(Context context) {
        mAppContext = context.getApplicationContext();
    }

    public static SearchHistory getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SearchHistory(context);
        }
        return mInstance;
    }

    private SharedPreferences getSharedPreferences() {
//        String spName = PREF_SEARCH_NAME + SharedPreferenceUtil.getUid(mAppContext);
        String spName = PREF_SEARCH_NAME;
        return mAppContext.getSharedPreferences(spName, Context.MODE_PRIVATE);
    }

    /**
     * 从 sp中记取历史记录
     *
     * @return
     */
    private HistoryList readHistoryFromSP() {
        HistoryList historyList = null;
        try {
            SharedPreferences sp = getSharedPreferences();
            String val = sp.getString(PREF_KEY_HISTORY, "");
            Gson gson = new Gson();
            historyList = gson.fromJson(val, HistoryList.class);
        } catch (Exception e) {
        }
        return historyList;
    }

    /**
     * 保存历史记录到sp中
     */
    private void saveHistory2Sp() {
        try {
            HistoryList historyList = mHistory.get();
            SharedPreferences.Editor spe = getSharedPreferences().edit();
            String json = "";
            if (historyList != null && historyList.historyList != null) {
                Gson gson = new Gson();
                json = gson.toJson(mHistory.get());
            }
            spe.putString(PREF_KEY_HISTORY, json);
            spe.commit();
        } catch (Exception e) {

        }

    }

    /**
     * 加载历史记录列表
     *
     * @return
     */
    public List<SearchHistoryEntity> loadSearchHistory() {
        if (mHistory.get() == null) {
            HistoryList historyList = readHistoryFromSP();
            if (historyList == null || historyList.historyList == null) {
                historyList = new HistoryList();
            }
            mHistory = new WeakReference<HistoryList>(historyList);
        }
        return mHistory.get().historyList;
    }


    /**
     * 添加历史记录
     *
     * @param searchHistory
     */
    public void add2History2(SearchHistoryEntity searchHistory) {
        HistoryList tmp = new HistoryList();
        if (mHistory.get() == null) {
            tmp.historyList = loadSearchHistory();
        } else {
            tmp.historyList = mHistory.get().historyList;
        }

        if (tmp.historyList != null && !tmp.historyList.isEmpty()) {
            if (tmp.historyList.get(0).equals(searchHistory)) {
                return;
            }
        }

        //只保存2条历史记录
        while (tmp.historyList.size() >= MAX_HISTORY_LEN) {
            tmp.historyList.remove(tmp.historyList.size() - 1);
        }

        tmp.historyList.add(0, searchHistory);

        mHistory = new WeakReference<HistoryList>(tmp);
        //
        saveHistory2Sp();
    }

    public void add2History(SearchHistoryEntity searchHistory) {
        //
        if (searchHistory == null || TextUtils.isEmpty(searchHistory.content)) {
            return;
        }

        HistoryList tmp = new HistoryList();
        if (mHistory.get() == null) {
            tmp.historyList = loadSearchHistory();
        } else {
            tmp.historyList = mHistory.get().historyList;
        }

        // 如果和第一条搜索记录相同刚不添加
        if (tmp.historyList != null && !tmp.historyList.isEmpty()) {
            if (tmp.historyList.get(0).equals(searchHistory)) {
                return;
            }
        }

        // 删除重复的记录
        while (tmp.historyList.contains(searchHistory)) {
            tmp.historyList.remove(searchHistory);
        }

        // 添加到最新一条搜索记录
        tmp.historyList.add(0, searchHistory);


        //如果超过默认长度，则删除后面的记录
        while (tmp.historyList.size() > MAX_HISTORY_LEN) {
            tmp.historyList.remove(tmp.historyList.size() - 1);
        }

        mHistory = new WeakReference<HistoryList>(tmp);
        //
        saveHistory2Sp();
    }

    /**
     * 清除历史记录
     */
    public void clearHistory() {
        mHistory = new WeakReference<HistoryList>(null);
        saveHistory2Sp();
    }

    /**
     *
     */
    public class HistoryList {
        List<SearchHistoryEntity> historyList = new ArrayList<SearchHistoryEntity>();

        HistoryList() {
        }

        HistoryList(List<SearchHistoryEntity> hl) {
            if (hl != null) {
                historyList.addAll(hl);
            }
        }

    }
}
